@page "/cache"
@using RestaurantFinder.Core.Services
@using RestaurantFinder.Core.Models
@inject ISearchCacheService CacheService
@inject ILogger<CacheManagement> Logger
@inject IJSRuntime JSRuntime

<PageTitle>缓存管理 - RestaurantFinder</PageTitle>

<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>
                    <i class="fas fa-database text-primary"></i>
                    缓存管理
                </h2>
                <div>
                    <button class="btn btn-outline-primary me-2" @onclick="RefreshStatistics">
                        <i class="fas fa-sync-alt"></i> 刷新
                    </button>
                    <button class="btn btn-outline-danger" @onclick="ClearAllCache">
                        <i class="fas fa-trash"></i> 清空缓存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="card border-primary">
                <div class="card-body text-center">
                    <div class="text-primary mb-2">
                        <i class="fas fa-list-ol fa-2x"></i>
                    </div>
                    <h5 class="card-title">缓存条目</h5>
                    <h3 class="text-primary">@statistics.TotalEntries</h3>
                    <small class="text-muted">个</small>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-4">
            <div class="card border-success">
                <div class="card-body text-center">
                    <div class="text-success mb-2">
                        <i class="fas fa-bullseye fa-2x"></i>
                    </div>
                    <h5 class="card-title">命中率</h5>
                    <h3 class="text-success">@($"{statistics.HitRate:P1}")</h3>
                    <small class="text-muted">@statistics.HitCount 次命中</small>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-4">
            <div class="card border-warning">
                <div class="card-body text-center">
                    <div class="text-warning mb-2">
                        <i class="fas fa-times-circle fa-2x"></i>
                    </div>
                    <h5 class="card-title">未命中</h5>
                    <h3 class="text-warning">@statistics.MissCount</h3>
                    <small class="text-muted">次</small>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-4">
            <div class="card border-info">
                <div class="card-body text-center">
                    <div class="text-info mb-2">
                        <i class="fas fa-memory fa-2x"></i>
                    </div>
                    <h5 class="card-title">内存使用</h5>
                    <h3 class="text-info">@FormatBytes(statistics.EstimatedMemoryUsage)</h3>
                    <small class="text-muted">估算值</small>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-chart-pie"></i>
                        缓存性能分析
                    </h5>
                </div>
                <div class="card-body">
                    @if (statistics.HitCount + statistics.MissCount > 0)
                    {
                        <div class="row">
                            <div class="col-md-6">
                                <h6>命中率分布</h6>
                                <div class="progress mb-3" style="height: 25px;">
                                    <div class="progress-bar bg-success" 
                                         role="progressbar" 
                                         style="width: @($"{statistics.HitRate:P0}")"
                                         aria-valuenow="@((int)(statistics.HitRate * 100))" 
                                         aria-valuemin="0" 
                                         aria-valuemax="100">
                                        命中 @($"{statistics.HitRate:P1}")
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h6>总请求数</h6>
                                <p class="h4 text-primary">@(statistics.HitCount + statistics.MissCount)</p>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <h6>缓存效果</h6>
                                @if (statistics.HitRate >= 0.8)
                                {
                                    <span class="badge bg-success">
                                        <i class="fas fa-check-circle"></i> 优秀
                                    </span>
                                    <small class="text-muted ms-2">缓存效果很好，大幅减少了API调用</small>
                                }
                                else if (statistics.HitRate >= 0.5)
                                {
                                    <span class="badge bg-warning">
                                        <i class="fas fa-exclamation-triangle"></i> 一般
                                    </span>
                                    <small class="text-muted ms-2">缓存有一定效果，可考虑调整缓存策略</small>
                                }
                                else
                                {
                                    <span class="badge bg-danger">
                                        <i class="fas fa-times-circle"></i> 需要优化
                                    </span>
                                    <small class="text-muted ms-2">缓存命中率较低，建议检查缓存配置</small>
                                }
                            </div>
                            <div class="col-md-6">
                                <h6>节省的API调用</h6>
                                <p class="h4 text-success">@statistics.HitCount 次</p>
                                <small class="text-muted">避免了高德地图API调用，节省了配额和响应时间</small>
                            </div>
                        </div>
                    }
                    else
                    {
                        <div class="text-center text-muted py-4">
                            <i class="fas fa-info-circle fa-2x mb-3"></i>
                            <p>暂无缓存使用数据</p>
                            <p class="small">进行一些餐厅搜索后，这里将显示缓存性能统计信息</p>
                        </div>
                    }
                </div>
            </div>
        </div>
    </div>

    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-cog"></i>
                        缓存配置说明
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6>缓存策略</h6>
                            <ul class="list-unstyled">
                                <li><i class="fas fa-check text-success"></i> 基于位置和搜索半径的智能缓存</li>
                                <li><i class="fas fa-check text-success"></i> 自动过期机制（默认30分钟）</li>
                                <li><i class="fas fa-check text-success"></i> 位置容差优化（默认100米）</li>
                                <li><i class="fas fa-check text-success"></i> 内存使用量控制</li>
                            </ul>
                        </div>
                        <div class="col-md-6">
                            <h6>性能优化</h6>
                            <ul class="list-unstyled">
                                <li><i class="fas fa-rocket text-primary"></i> 减少API调用频次</li>
                                <li><i class="fas fa-tachometer-alt text-primary"></i> 提高响应速度</li>
                                <li><i class="fas fa-shield-alt text-primary"></i> 降低API配额消耗</li>
                                <li><i class="fas fa-leaf text-primary"></i> 减少网络流量</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@code {
    private CacheStatistics statistics = new();
    private bool isLoading = false;

    protected override async Task OnInitializedAsync()
    {
        await RefreshStatistics();
    }

    private async Task RefreshStatistics()
    {
        try
        {
            isLoading = true;
            StateHasChanged();
            
            statistics = await CacheService.GetCacheStatisticsAsync();
            Logger.LogInformation("缓存统计信息已刷新");
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "刷新缓存统计信息时发生错误");
            await JSRuntime.InvokeVoidAsync("alert", "刷新缓存统计信息失败，请稍后重试");
        }
        finally
        {
            isLoading = false;
            StateHasChanged();
        }
    }

    private async Task ClearAllCache()
    {
        try
        {
            var confirmed = await JSRuntime.InvokeAsync<bool>("confirm", 
                "确定要清空所有缓存吗？这将删除所有已缓存的搜索结果。");
            
            if (confirmed)
            {
                await CacheService.ClearAllCacheAsync();
                await RefreshStatistics();
                
                Logger.LogInformation("所有缓存已清空");
                await JSRuntime.InvokeVoidAsync("alert", "缓存已清空");
            }
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "清空缓存时发生错误");
            await JSRuntime.InvokeVoidAsync("alert", "清空缓存失败，请稍后重试");
        }
    }

    private static string FormatBytes(long bytes)
    {
        if (bytes < 1024) return $"{bytes} B";
        if (bytes < 1024 * 1024) return $"{bytes / 1024.0:F1} KB";
        if (bytes < 1024 * 1024 * 1024) return $"{bytes / (1024.0 * 1024.0):F1} MB";
        return $"{bytes / (1024.0 * 1024.0 * 1024.0):F1} GB";
    }
} 